<template>
  <div class="chat">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back" @click="goBack">＜</div>
      <div class="title">在线问诊</div>
      <div class="notification-icon">🔔</div>
      <div class="notification">
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-container" ref="chatContainer">
      <!-- 聊天记录 -->
      <div
        v-for="(msg, index) in allMessages"
        :key="index"
        class="message"
        :class="getMessageClass(msg)"
      >
        <div class="message-avatar">
          {{ getMessageSender(msg) }}
        </div>
        <div
          class="message-content"
          :class="{'prescription-card': msg.isPrescription}"
          @click="msg.isPrescription && handlePrescriptionClick(msg)"
        >
          <template v-if="msg.isPrescription">
            <div class="prescription-header">
              <i class="el-icon-document-checked"></i>
              <span>电子处方</span>
            </div>
            <div class="prescription-body">{{ msg.content }}</div>
          </template>
          <template v-else>
            {{ msg.content || msg.message }}
          </template>
        </div>
      </div>
    </div>

    <!-- 底部输入区域 -->
    <div class="input-area">
      <div class="input-box">

        <input
          v-model="inputMessage"
          type="text"
          placeholder="请输入要发送给医生的内容"
          @keyup.enter="handleSend"
        >
        <div class="send-btn" @click="handleSend">发送</div>
        <div class="video-call" @click="startVideoCall">
          <img src="@/assets/images/屏幕截图 2025-03-08 115150.png" alt="视频通话" width="24" height="24"/>
        </div>
      </div>
      <div v-if="showVideoCall" class="video-call-dialog">
        <div class="video-call-content">
          <h3>视频通话请求</h3>
          <p>收到来自医生的视频通话请求</p>
          <div class="video-call-actions">
            <button class="accept-btn" @click="acceptVideoCall">接受</button>
            <button class="reject-btn" @click="rejectVideoCall">拒绝</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加处方详情弹窗 -->
    <el-dialog
      title="处方详情"
      :visible.sync="showPrescriptionDetail"
      width="50%">
      <div v-if="prescriptionDetail" class="prescription-detail">
        <div class="detail-item">
          <span class="label">患者姓名：</span>
          <span>{{ prescriptionDetail.name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">性别：</span>
          <span>{{ prescriptionDetail.sex }}</span>
        </div>
        <div class="detail-item">
          <span class="label">年龄：</span>
          <span>{{ prescriptionDetail.age }}岁</span>
        </div>
        <div class="detail-item">
          <span class="label">诊断结果：</span>
          <span>{{ prescriptionDetail.diagnosis }}</span>
        </div>
        <div class="detail-item">
          <span class="label">开具药品：</span>
          <div class="drug-item">
            {{ prescriptionDetail.drugName }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getDoctorName} from '@/api/doctor/doctor'
import { historicalPrescriptionDetails } from '@/api/doctorTerminal/myPharmacy/historicalPrescription'

export default {
  name: 'Chat',

  data() {
    return {
      showVideoCall: false,
      pendingVideoCall: null,
      inputMessage: '',
      hasNewMessage: false,
      websocket: null,
      doctorName: "",
      chatContent: '',
      messageList: [],
      charHistory: [],  //保存医生和患者之间的聊天记录
      wsAddress: 'ws://localhost:1212',
      currentDoctor: {
        doctorId: '1', // 默认医生ID
        doctorName: '主治医生' // 默认医生名称
      },
      allMessages: [],  // 确保这个数组已经定义
      chatMessages: [], // 聊天消息数组
      showPrescriptionDetail: false,
      prescriptionDetail: null,
    }
  },

  created() {
    this.giveDoctorName()
    this.connectWebsocket(this.currentDoctor)
    // 在组件创建时获取本地存储的聊天记录
    const storedMessages = localStorage.getItem('chatMessages');
    if (storedMessages) {
      this.chatMessages = JSON.parse(storedMessages);
      console.log('从本地存储加载的聊天记录:', this.chatMessages);

      // 将历史聊天记录添加到当前页面的消息列表中
      this.allMessages = [...this.allMessages, ...this.chatMessages.map(msg => ({
        type: msg.type,
        content: msg.content,
        name: msg.type === 'doctor' ? this.currentDoctor.doctorName : undefined,
        time: new Date().toLocaleTimeString()
      }))];

      // 滚动到最新消息
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    }
  },

  methods: {
    //获取医生名称
    giveDoctorName() {
      getDoctorName().then(response => {
        this.currentDoctor.doctorName = response;
        console.log(response)
      }).catch(error => {
        console.error('获取医生名称失败:', error);
      });
    },
    acceptVideoCall() {
      if (!this.pendingVideoCall) return;

      // 构建视频通话 URL
      const protocol = 'https:';
      const host = window.location.hostname;
      const port = '8087';
      const url = `/toMeeting?userId=患者&roomId=${this.pendingVideoCall.roomId}`;
      const fullUrl = `${protocol}//${host}:${port}${url}`;

      // 打开视频通话窗口
      const windowFeatures = 'width=800,height=600,menubar=no,toolbar=no,location=no,status=no';
      window.open(fullUrl, '_blank', windowFeatures);

      this.showVideoCall = false;
      this.pendingVideoCall = null;
    },

    rejectVideoCall() {
      if (!this.pendingVideoCall) return;

      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(JSON.stringify({
          code: 10002,
          type: 1,
          nickname: "患者",
          target: "医生",
          content: "患者拒绝了视频通话",
          messageType: "video_call_reject"
        }));
      }

      this.showVideoCall = false;
      this.pendingVideoCall = null;
    },

    async recording(chatData) {
      try {
        const recordData = {
          content: chatData.content || this.allMessages.map(msg => ({
            type: msg.type,
            content: msg.content,
            time: msg.time
          })),
          doctorPersonal: chatData.doctorPersonal || [{
            doctorName: this.currentDoctor?.doctorName,
            // 其他医生相关信息
          }]
        };

      } catch (error) {
        console.error('记录聊天历史失败：', error);
      }
    },

    async sendOfflineMessage() {
      if (this.currentDoctor && this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        try {
          // 发送患者下线消息
          this.websocket.send(JSON.stringify({
            "code": "10004",
            "nickname": "患者",
            "target": this.currentDoctor.doctorName
          }));

          // 发送医生下线消息
          this.websocket.send(JSON.stringify({
            "code": "10004",
            "nickname": this.currentDoctor.doctorName,
            "target": "患者"
          }));

          await new Promise(resolve => setTimeout(resolve, 200));

          this.websocket.close();
          this.websocket = null;

          this.currentDoctor = null;
          this.allMessages = [];
          this.messageList = [];

          // 记录聊天历史
          await this.recording({
            content: this.allMessages,
            doctorPersonal: [this.currentDoctor]
          });
        } catch (error) {
          console.error('发送下线消息失败:', error);
        }
      }
    },

    async goBack() {
      await this.beforeRouteLeave()
      await this.sendOfflineMessage();
      this.$router.back();
    },

    async scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },

    connectWebsocket(doctor) {
      if (this.websocket != null && this.websocket.readyState === 1) {
        return;
      }

      this.websocket = new WebSocket(this.wsAddress);

      this.websocket.onopen = (evt) => {
        this.websocket.send(JSON.stringify({
          "code": "10001",
          "nickname": "患者"
        }));

        this.websocket.send(JSON.stringify({
          "code": "10003",
          "nickname": "患者",
        }));

        this.allMessages.push({
          type: 'system',
          content: `您已连接到${doctor.doctorName}，可以开始咨询了`
        });
      };

      this.websocket.onmessage = evt => {
        try {
          console.log('患者端收到原始消息：', evt.data);
          const data = JSON.parse(evt.data);
          console.log('患者端解析后的消息：', data);

          // 通过消息内容判断是否为处方消息
          if (data.message && data.message.includes('处方信息：')) {
            console.log('收到处方消息：', data);
            const prescriptionMsg = {
              type: 'doctor',
              content: data.message,
              name: data.name,
              time: data.time,
              isPrescription: true,
              prescriptionData: {
                diagnosis: data.message.split('诊断结果：')[1]?.split('\n')[0] || '',
                drugNames: [data.message.split('开具药品：')[1]?.split('\n')[0] || '']
              }
            };

            this.allMessages.push(prescriptionMsg);

            // 保存到本地存储
            const storedMessages = [...(this.chatMessages || []), prescriptionMsg];
            localStorage.setItem('chatMessages', JSON.stringify(storedMessages));
            this.chatMessages = storedMessages;

            this.scrollToBottom();
            return;
          }

          // 处理普通消息
          if (data.code === "10002") {
            const message = {
              type: data.nickname === "医生" ? 'doctor' : 'user',
              content: data.message || data.content,
              name: data.nickname,
              target: data.target,
              messageType: data.messageType,
              code: data.code,
              time: new Date().toLocaleTimeString(),
              self: false
            };

            console.log('构造的普通消息：', message);
            this.allMessages.push(message);
            this.scrollToBottom();
          } else if (data.name === "系统消息") {
            this.allMessages.push({
              type: 'system',
              content: data.message,
              time: new Date().toLocaleTimeString()
            });
          }

          this.scrollToBottom();
        } catch (error) {
          console.error('消息处理错误：', error);
          console.error('错误消息内容：', evt.data);
        }
      };

      this.websocket.onerror = evt => {
        console.log("websocket错误：", evt);
        this.$message.error('连接出错，请重试');
      };

      this.websocket.onclose = async evt => {
        console.log("websocket关闭：", evt);
        if (this.currentDoctor) {
          this.$message.info('连接已断开');
          // 记录聊天历史
          await this.recording({
            content: this.allMessages,
            doctorPersonal: [this.currentDoctor]
          });
        }
      };
    },

    async sendChatMessage(type) {
      if (!this.inputMessage.trim()) {
        this.$message.error('请输入消息内容');
        return;
      }

      try {
        if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
          this.$message.error('连接已断开，请重新连接');
          return;
        }

        const message = {
          type: 'user',
          content: this.inputMessage,
          time: new Date().toLocaleTimeString(),
        };
        this.allMessages.push(message);

        const messageData = {
          "code": "10002",
          "nickname": "患者",
          "content": this.inputMessage,
          "target": this.currentDoctor.doctorName,
          "type": type
        };
        this.charHistory.push(messageData)
        this.websocket.send(JSON.stringify(messageData));
        this.inputMessage = '';
        await this.scrollToBottom();
      } catch (error) {
        console.error('发送消息失败:', error);
        this.$message.error('发送失败，请重试');
      }
    },

    async handleSend() {
      if (!this.inputMessage.trim()) {
        this.$message.error('请输入内容');
        return;
      }

      await this.sendChatMessage(1);
    },

    getMessageClass(msg) {
      const baseClass = {
        'user-message': msg.type === 'user',
        'doctor-message': msg.type === 'doctor',
        'system-message': msg.type === 'system',
        'prescription-card': msg.isPrescription
      };
      return baseClass;
    },

    getMessageSender(msg) {
      if (msg.type === 'doctor') {
        return '医生'
      } else if (msg.type === 'user') {
        return '患者'
      } else if (msg.type === 'system') {
        return '系统'
      }
      return '医生'
    },

    async startVideoCall() {
      if (!this.currentDoctor) {
        this.$message.error('请先选择医生');
        return;
      }

      try {
        const roomId = `2-${Date.now()}`;

        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
          this.websocket.send(JSON.stringify({
            code: 10002,
            type: 1,
            nickname: "患者",
            target: this.currentDoctor.doctorName,
            content: roomId,
            messageType: "video_call"
          }));
        }

        const protocol = 'https:';
        const host = window.location.hostname;
        const port = '8087';
        const url = `/toMeeting?userId=患者&roomId=${roomId}`;
        const fullUrl = `${protocol}//${host}:${port}${url}`;

        const windowFeatures = 'width=800,height=600,menubar=no,toolbar=no,location=no,status=no';
        window.open(fullUrl, '_blank', windowFeatures);

      } catch (error) {
        console.error('视频通话发起失败:', error);
        this.$message.error('视频通话发起失败，请重试');
      }
    },

    // 修改处方点击处理方法
    handlePrescriptionClick(msg) {
      if (msg.isPrescription) {
        const prescriptionId = localStorage.getItem('savePrescriptionId');
        console.log('获取到的处方ID:', prescriptionId);

        if (prescriptionId) {
          historicalPrescriptionDetails(prescriptionId).then(response => {
            console.log('API返回的完整响应:', response);

            if (response && response.data) {
              this.prescriptionDetail = {
                name: response.data.name || '未知',
                sex: response.data.sex || '未知',
                age: response.data.age || '未知',
                diagnosis: response.data.diagnosis || '暂无诊断信息',
                drugName: response.data.drugName || '暂无药品信息' // 直接使用drugName字段
              };
              this.showPrescriptionDetail = true;
            } else {
              console.error('API返回数据格式不正确:', response);
              this.$message.error('处方数据格式不正确');
            }
          }).catch(error => {
            console.error('获取处方详情失败:', error);
            this.$message.error('获取处方详情失败，请重试');
          });
        } else {
          console.warn('未找到处方ID');
          this.$message.warning('未找到处方信息');
        }
      }
    },
  },

  beforeRouteLeave(to, from, next) {
    this.sendOfflineMessage().then(() => {
      next();
    });
  },

  mounted() {
    window.addEventListener('beforeunload', (event) => {
      event.preventDefault();
      this.sendOfflineMessage();
      event.returnValue = '';
    });

    // 添加连接状态检查
    this.checkConnection = setInterval(() => {
      if (this.websocket && this.websocket.readyState !== WebSocket.OPEN) {
        console.log('WebSocket连接已断开，尝试重新连接...');
        this.connectWebsocket();
      }
    }, 5000);
  },

  destroyed() {
    window.removeEventListener('beforeunload', this.sendOfflineMessage);
  }
}
</script>

<style scoped lang="scss">
.chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;

  .header {
    height: 44px;
    background-color: #4a90e2;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 16px;
    position: relative;

    .back {
      font-size: 20px;
      padding: 8px;
      margin-left: -8px;
    }

    .title {
      flex: 1;
      text-align: center;
      font-size: 18px;
    }

    .notification {
      padding: 8px;
      margin-right: -8px;
    }
  }

  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    background-color: #f5f5f5;

    .message {
      margin-bottom: 16px;
      display: flex;
      align-items: flex-start;

      .message-avatar {
        min-width: 24px;       // 更小的尺寸
        height: 24px;          // 更小的尺寸
        border-radius: 2px;    // 非常小的圆角，接近方形
        background: #f5f5f5;   // 浅灰色背景
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 8px;         // 调整边距
        font-size: 12px;       // 字体大小
        color: #333;          // 更深的文字颜色
        border: none;         // 移除边框
      }

      .message-content {
        padding: 8px 12px;
        border-radius: 8px;
        max-width: 70%;
      }
    }

    .user-message {
      flex-direction: row-reverse;
      justify-content: flex-start;

      .message-content {
        background-color: #4a90e2;
        color: white;
      }

      .message-avatar {
        background-color: #f5f5f5;  // 保持一致的灰色背景
        color: #333;               // 保持一致的文字颜色
      }
    }

    .ai-message, .doctor-message {
      .message-content {
        background-color: white;
        color: #333;
      }
    }

    .doctor-message {
      flex-direction: row;  // 医生消息靠左显示
      justify-content: flex-start;

      .message-avatar {
        background-color: #f5f5f5;  // 与用户头像使用相同的灰色背景
        color: #333;               // 使用相同的文字颜色
      }

      .message-content {
        background-color: white;
        color: #333;
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        padding: 12px 15px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        min-width: 200px;  // 设置最小宽度

        // 添加悬停效果
        &:hover {
          background-color: #f8f9fa;
          border-color: #d4d4d4;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }

        // 添加医生图标
        &::before {
          content: '👨‍⚕️';  // 使用医生emoji
          margin-right: 8px;
          font-size: 16px;
        }
      }
    }

    .system-message {
      justify-content: center;  // 系统消息居中显示

      .message-content {
        background-color: #fff3e0;
        color: #666;
        font-size: 12px;
        text-align: center;
        margin: 10px auto;
        border: none;
        box-shadow: none;
      }

      .message-avatar {
        display: none;  // 系统消息不显示头像
      }
    }
  }

  .input-area {
    background-color: white;
    padding: 12px 16px;
    border-top: 1px solid #eee;

    .input-box {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      border-radius: 4px;
      padding: 8px 12px;
      margin-bottom: 12px;

      input {
        flex: 1;
        border: none;
        background: none;
        font-size: 14px;
        padding: 0;
        margin: 0;
        outline: none;

        &::placeholder {
          color: #999;
        }
      }

      .send-btn {
        color: #4a90e2;
        font-size: 14px;
        padding: 4px 8px;
        cursor: pointer;
        .video-call:hover{
          color: #4a90e2;
          font-size: 14px;
          padding: 4px 8px;
          cursor: pointer;
        }
        &:active {
          opacity: 0.8;
        }
      }
    }

    .quick-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .action-buttons {
      display: flex;
      justify-content: space-around;

      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 12px;
        color: #666;
        cursor: pointer;



        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .video-call {
    margin-left: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      background-color: rgba(74, 144, 226, 0.1);
    }

    img {
      width: 24px;
      height: 24px;
    }
  }

  .video-call-dialog {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 9999;
    min-width: 300px;
    border: 2px solid #4a90e2;
  }

  .video-call-content {
    text-align: center;
  }

  .video-call-content h3 {
    margin-bottom: 10px;
    color: #333;
  }

  .video-call-content p {
    margin-bottom: 20px;
    color: #666;
  }

  .video-call-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
  }

  .accept-btn {
    padding: 8px 24px;
    background-color: #4a90e2;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
  }

  .reject-btn {
    padding: 8px 24px;
    background-color: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
  }

  .accept-btn:hover {
    background-color: #357abd;
  }

  .reject-btn:hover {
    background-color: #e8e8e8;
  }

  .prescription-card {
    cursor: pointer;

    .prescription-content {
      background-color: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      padding: 15px;
      margin: 10px 0;
      white-space: pre-line;

      &:hover {
        background-color: #e9ecef;
      }
    }
  }

  .prescription-detail {
    padding: 20px;

    .detail-item {
      margin-bottom: 15px;

      .label {
        font-weight: bold;
        color: #4a90e2;
        margin-right: 10px;
      }
    }

    .drug-item {
      margin: 10px 0;
      padding: 10px;
      background-color: #f8f9fa;
      border-radius: 4px;
    }
  }
}
</style>
